<!--
 * @Descripttion: 轮播图维护
 * @version: 
 * @Author: 穆宏宇
 * @Date: 2020-11-23 13:56:38
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-24 14:25:25
-->
<!-- 带图片上传 -->
<template>
	<div class="bigDiv">
		<el-form :model="queryParams" ref="queryForm" :inline="true" label-width="88px">
			<div class="topNav">
				<el-button type="text" icon="el-icon-plus" @click="openDialogEdit()">新增</el-button>
			</div>
		</el-form>
		
		<el-table :data="tableData" ref="table" style="width: 100%" row-key="id" border height="calc(100vh - 220px)">
			<el-table-column minWidth="300px" prop="name" label="排序">
			</el-table-column>
			<el-table-column width="170px" label="专区图片">
				<template slot-scope="scope">
					<img :src="scope.row.url" width="50px" />
				</template>
			</el-table-column>
			<el-table-column label="操作" width="470">
				<template slot-scope="scope">
					<el-button type="primary" size="mini" @click="openDialogEdit(scope.row)">
						修改
					</el-button>
					<el-button type="primary" size="mini" @click="deleteIt(scope.row)">
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		
		
		<el-pagination
		  @size-change="handleSizeChange"
		  @current-change="handleCurrentChange"
		  :current-page="queryParams.currentPage"
		  :page-size="queryParams.pageSize"
		  layout="total, sizes, prev, pager, next, jumper"
		  :total="queryParams.total"
		></el-pagination>
		
		<!-- 增改查 -->
		<el-dialog :title="title" :visible.sync="dialogVisible" width="580px">
			<el-form ref="form" :model="form" label-width="110px" :rules="rules" label-suffix=":">
				
				<el-form-item label="特色专区名称" prop="name">
					<el-input v-model="form.name"></el-input>
				</el-form-item>
				<el-form-item label="主要图片上传" prop="url">
					<el-input style="display:none" v-model="form.url"></el-input>
					<el-upload :class="{'limited':showFlag||(mainFileList&&mainFileList.length>=1)}"
						list-type="picture-card" :action="fileUrl" :data="{ fileType: 14,objectName:'banner' }" :on-preview="handlePreview"
						:on-remove="mainHandleRemove" :before-remove="beforeRemove"
						:on-success="mainHandleAvatarSuccess" :on-error="handleAvatarError"
						:before-upload="beforeAvatarUpload" :headers="fileHeaders" :limit="1" :on-exceed="handleExceed1"
						:file-list="mainFileList" :disabled="showFlag">
						<i class="el-icon-plus"></i>
						<div slot="tip" class="el-upload__tip">
							<p>
								请上传1个图片，图片格式要求jpg/png格式，且不超过500kb
							</p>
						</div>
					</el-upload>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="save()">保 存</el-button>
			</span>
		</el-dialog>
		
	</div>
</template>

<script>
	import {
		beforeUpload
	} from "@/util/common";
	// 上传文件
	import fileUpdata from "@/api/file.config2";
	import moment from "moment";
	import {
		Base64
	} from "js-base64";
	import tools from "@/tools";
	import {
		deleteFile,
		removeByUrls,
		getFileUrl
	} from "@/api/common.api";
	import {
		// characteristicareaList,
		// addCharacteristicarea,
		// editCharacteristicarea,
		// deleteCharacteristicarea,
		
		selectTBannerList,
		addBanner,
		editBanner,
		deleteTBannerById,
		deleteBanner
	} from '@/api/admin.api'


	export default {
		name: 'catalogue-manager',
		data() {
			return {
				env: process.env.NODE_ENV === 'development' ? 'dev' : 'pro',
				tableData: [],
				dialogVisible: false,
				// 上传一般图片数据
				fileList: [],
				// 上传主要图片数据
				mainFileList: [],
				fileUrl: "",
				showFlag: false,
				fileHeaders: {},
				rules: {
					name: [{
						required: true,
						trigger: 'blur',
						message: '请输入专区名称'
					}],
					url: [{
						required: true,
						trigger: 'change',
						message: '请选择分类图片'
					}],
				},
				queryParams:{
					pageNum:1,
					pageSize:10,
					currentPage:1
				},
				title:'',
				form: {
					name: '',
					url: ''
				},
			}
		},
		computed: {
			// 表格高度
			maxHeightNow() {
				const height = window.innerHeight
				return height - 162
			}
		},
		mounted() {

			this.fileHeaders = {
				...fileUpdata.headers()
			};
			this.fileUrl = fileUpdata.url;
			
			this.getList();

		},
		methods: {
			handleSizeChange(val) {
				this.queryParams.pageSize = val
				this.getList()
			},
			handleCurrentChange(val) {
				this.queryParams.pageNum = val
				this.getList()
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
				console.log(val)
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.currentPage = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			
			getList(){
				var that = this;
				selectTBannerList(this.queryParams).then(res=>{
					that.tableData = res.rows;
					that.queryParams.total = res.total;
				})
			},
			deleteIt(row) {
				var that = this;
				let pid = row.parentCategoryId || ''
				this.$alert(`确定删除吗？`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'success',
					callback: action => {
						if (action === 'confirm') {
							deleteBanner(row).then(res => {
								if(res.code == 200){
									that.$message.success("删除成功");
									that.handleQuery()
								}else{
									that.$message.error("删除失败");
								}
							})
						}
					}
				})
			},
			/**
			 * @description 上传的图片格式和大小
			 * @author 穆宏宇
			 * @date 2020-09-14 11:22:21
			 * @param
			 * @return
			 * */
			beforeAvatarUpload(file) {
				const typeList = ["png", "jpg"];
				const isJPG = beforeUpload(file, typeList);
				const isLt5kb = file.size / 1024 < 4024;
				if (!isJPG) {
					this.$message.error("上传文件格式不符合!");
				}
				if (!isLt5kb) {
					this.$message.error("上传图片大小不能超过 500kb!");
				}
				return isJPG && isLt5kb;
			},
			// 上传错误文件时提示
			handleAvatarError(res, file) {
				this.$message.error("文件上传失败，请重试");
			},
			mainHandleAvatarSuccess(res, file) {
				
				this.form.url = res.data;
				const curFile = {
					name: res.data,
					url: res.data,
					id: res.data,
					fileType: res.data,
				};
				this.mainFileList.push(curFile);
				const ids = [];
				this.mainFileList.map((item) => {
					ids.push(item.id);
				});
			},
			/**
			 * @functionName submitUploadEditor
			 * @desccription 富文本批量上传图片
			 * @author 穆宏宇
			 * @date 2021-04-09 10:21:23
			 * @version v1.0.0
			 */
			submitUploadEditor() {
				if (this.fileDataEditor.length === 0) {
					this.$message({
						message: "请选择一般图片",
						type: 'warning'
					});
					return
				}
				if (this.goodsDescFileList.length + this.fileDataEditor.length > 10) {
					this.$message.warning(
						`最多可上传10张图片，您已超限`
					)
					return
				}
				const formData = new FormData(); // new formData对象
				this.$refs.upload.submit(); // 提交调用uploadFile函数
				formData.append('Authorization', tools.localRead('access_token')); // 添加token
				this.fileDataEditor.forEach(item => {
					formData.append("fileList", item.raw);
				})

				formData.append("fileType", 14);
				uploadMultipleFiles(formData).then(res => {
					this.$message({
						message: "上传成功",
						type: 'success'
					});
					res.forEach(item => {
						const {
							submittedFileName,
							id,
							url,
							fileType
						} = item
						// 获取光标所在位置
						let length = this.quill.getSelection().index;
						// 插入图片 res.url为服务器返回的图片地址
						this.quill.insertEmbed(length, "image", url);
						// 调整光标到最后
						this.quill.setSelection(length + 1);
						// this.goodsDescFileList.push({name: submittedFileName, id, url, fileType})
					})
					this.goodsDescFileList = [];
					this.fileDataEditor = []
				})
			},
			submitUpload() {
				if (this.fileData.length === 0) {
					this.$message({
						message: "请选择一般图片",
						type: 'warning'
					});
					return
				}
				if (this.fileList.length + this.fileData.length > 10) {
					this.$message.warning(
						`最多可上传10张图片，您已超限`
					)
					return
				}
				const formData = new FormData(); // new formData对象
				this.$refs.upload.submit(); // 提交调用uploadFile函数
				formData.append('Authorization', tools.localRead('access_token')); // 添加token
				this.fileData.forEach(item => {
					formData.append("fileList", item.raw);
				})

				formData.append("fileType", 14);
				uploadMultipleFiles(formData).then(res => {
					this.$message({
						message: "上传成功",
						type: 'success'
					});
					res.forEach(item => {
						const {
							submittedFileName,
							id,
							url,
							fileType
						} = item
						this.fileList.push({
							name: submittedFileName,
							id,
							url,
							fileType
						})
					})
					this.fileData = []
				})
			},
			// 上传文件
			uploadFile(file, fileList) {
				// console.log({file,fileList});
				// this.fileData.push(file.file);  // append增加数据
			},
			//监控上传文件列表
			handleChange(file, fileList) {
				this.fileData.push(file)
			},
			handleAvatarSuccess(res, file, fileList) {
				console.log(fileList)
				const {
					submittedFileName,
					id,
					url,
					fileType
				} = res.data;
				this.fileList.push({
					name: submittedFileName,
					id,
					url,
					fileType
				})
				const ids = [];
				this.fileList.map((item) => {
					ids.push(item.id);
				});
				this.formData.attachmentId = ids.toString();
			},
			// 预览附件
			handlePreview(file) {
				console.log('预览', file);
				if (file.response && file.response.data) {
					const {
						fileType,
						id
					} = file.response.data
					file['fileType'] = fileType
					file['id'] = id
				}
				getFileUrl(file.fileType, file.id).then(res => {
					this.dialogImageUrl = res
					this.dialogVisible = true
				})
			},
			// 取消上传图片
			mainHandleRemove(file, fileList) {
				if (file && file.status === "success") {
					const data = {
						urls: [file.url],
					};
					removeByUrls(data).then((res) => {
						const index = this.mainFileList.findIndex(item => item.url === file.url);
						this.mainFileList.splice(index, 1);
						this.form.url = '';
					});
				}
			},
			handleRemove(file, fileList) {
				const index = this.fileList.findIndex(item => item.uid === file.uid);
				if (index > -1) {
					this.fileList.splice(index, 1);
				}
				const dataIndex = this.fileData.findIndex(item => item.uid === file.uid);
				if (dataIndex > -1) {
					this.fileData.splice(dataIndex, 1);
				}
			},
			editorHandleRemove(file, fileList) {
				// console.log({file, fileList})
				// this.fileDataEditor = this.fileDataEditor.filter(item=>item.uid != )
				// this.goodsDescFileList = this.goodsDescFileList.filter(item=>item.url !== file.url)
			},
			// 选中上传图片限制
			handleExceed1(files, fileList) {
				this.$message.warning(
					`最多可上传1张图片，您已超限`
				)
			},
			handleExceed10(files, fileList) {
				this.$message.warning(
					`最多可上传10张图片，您已超限`
				)
			},

			// 移除上传图片
			beforeRemove(file, fileList) {
				if (file && file.status === "success") {
					return this.$confirm(`确定移除 ${file.name}？`);
				}

			},
			openDialogEdit(row) {
				if(row && row.id){
					this.title = "修改";
					this.form = row;
					this.form.id = row.id;
					
					this.mainFileList = [{
						name: '',
						url: row.url,
						id: '',
						fileType: 14,
					}];
				}else{
					this.title = "新增";
					this.form = {}
					this.mainFileList = [];
				}  
				
				this.dialogVisible = true
			},
			save() {
				var that = this;
				that.$refs.form.validate((valid) => {
					if (valid) {
						if(that.form.id){
							editBanner(that.form).then(res => {
								if (res.code == 200) {
									that.$message.success("修改成功");
									that.handleQuery();
									that.dialogVisible = false;
								}else{
									that.$message.success("添加失败");
								}
							})
						}else{
							addBanner(that.form).then(res => {
								if (res.code == 200) {
									that.$message.success("添加成功");
									that.handleQuery();
									that.dialogVisible = false;
								}else{
									that.$message.success("添加失败");
								}
							})
						}
						
					}
				})
			}
		}
	}
</script>

<style lang='scss'>
	.catalogue-manager {

		th,
		td,
		tr {
			text-align: left !important;
			padding-left: 40px;
			padding-right: 40px;
		}

		.mb10 {
			margin-bottom: 10px;
		}
	}
</style>
